package com.junzhiit.nengji.shop.service.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.junzhiit.nengji.bo.ShopBO;
import com.junzhiit.nengji.dao.AddressDAO;
import com.junzhiit.nengji.dao.ShopDAO;
import com.junzhiit.nengji.dao.ShopDeliveryDAO;
import com.junzhiit.nengji.model.Address;
import com.junzhiit.nengji.model.ShopDelivery;
import com.junzhiit.nengji.model.enums.ShopDeliveryType;
import com.junzhiit.nengji.model.enums.ShopDeliveryVehicle;
import com.junzhiit.nengji.shop.service.ShopDeliveryService;
import com.junzhiit.nengji.shop.web.exception.AddressNotFoundException;
import com.junzhiit.nengji.shop.web.exception.ShopDeliveryNotFoundException;
import com.junzhiit.nengji.shop.web.exception.ShopDeliveryNotWithinScopeException;
import com.junzhiit.nengji.shop.web.exception.ShopNotFoundException;
import com.junzhiit.nengji.shop.web.util.AmapUtil;
import com.junzhiit.nengji.shop.web.vo.ResultVO;
import com.junzhiit.nengji.shop.web.vo.ShopDeliveryInfoVO;

@Service
public class ShopDeliveryServiceImpl extends BaseServiceImpl implements ShopDeliveryService {
	
	@Autowired
	private ShopDeliveryDAO shopDeliveryDAO;
	
	@Autowired
	private AddressDAO addressDAO;
	
	@Autowired
	private ShopDAO shopDAO;

	@Override
	public int getTotalCount(String shopId) {
		return shopDeliveryDAO.getTotalCount(shopId);
	}

	@Override
	public ResultVO getShopDeliveryInfo(String addressId, String shopId) {
		/**
		 * 1.查询用户的地址
		 * 2.取得商户地址
		 * 3.取得商户配送信息
		 * 4.算出用户与商户之间的距离、时间(按照配送信息的工具计算) or 不适合配送？
		 * */
		ResultVO vo = new ResultVO();
		Address address = addressDAO.query(addressId);
		if(address == null){
			throw new AddressNotFoundException("用户地址不存在");
		}
		ShopBO shopBO= shopDAO.findShopById(shopId);
		if (shopBO == null) {
			throw new ShopNotFoundException("店铺不存在");
		}
		int count = shopDeliveryDAO.getTotalCount(shopId);
		if(count<=0){
			throw new ShopDeliveryNotFoundException("店铺没有配送信息");
		}
		address.setArea(address.getArea().replace(" ", ""));
		String shopAddress = shopBO.getProvince()+shopBO.getCity()+shopBO.getCounty()+shopBO.getAddress();
		shopAddress = shopAddress.replace(" ", "");
		AmapUtil.Location userLo = AmapUtil.latitudeLongitude(address.getArea()+address.getAddress());
		AmapUtil.Location shopLo = AmapUtil.latitudeLongitude(shopAddress);
		
		List<ShopDelivery> list = shopDeliveryDAO.findAllByShopId(shopId);
		Map<Integer,JSONObject> map = new HashMap<Integer,JSONObject>();
		Set<Integer> set = new HashSet<Integer>();
		Map<String,Object> mapResult = new HashMap<String,Object>();
		for(int i = 0;i<list.size();i++){
			ShopDelivery sd = list.get(i);
			set.add(sd.getVehicle());
		}
		//求出所拥有的交通工具类型下的距离和时间
		Iterator<Integer> iterator = set.iterator();
		while (iterator.hasNext()) {
			Integer current = iterator.next();
			if(current.equals(ShopDeliveryVehicle.BICYCLE.toIntValue())){
				JSONObject obj = AmapUtil.walking(shopLo, userLo);
				map.put(ShopDeliveryVehicle.BICYCLE.toIntValue(), obj);
			}else if(current.equals(ShopDeliveryVehicle.ELECTRIC_VEHICLE.toIntValue())){
				JSONObject obj = AmapUtil.bicycling(shopLo, userLo);
				map.put(ShopDeliveryVehicle.ELECTRIC_VEHICLE.toIntValue(), obj);
			}else if(current.equals(ShopDeliveryVehicle.TRANSIT.toIntValue())){
				JSONObject obj = AmapUtil.distanceMeasurement(shopLo, userLo, ShopDeliveryVehicle.TRANSIT.toIntValue());
				map.put(ShopDeliveryVehicle.TRANSIT.toIntValue(), obj);
			}else if(current.equals(ShopDeliveryVehicle.AUTOMOBILE.toIntValue())){
				JSONObject obj = AmapUtil.driving(shopLo, userLo);
				map.put(ShopDeliveryVehicle.AUTOMOBILE.toIntValue(), obj);
			}else{
				JSONObject obj = AmapUtil.distanceMeasurement(shopLo, userLo, ShopDeliveryVehicle.BICYCLE.toIntValue());
				map.put(ShopDeliveryVehicle.OTHER.toIntValue(), obj);
			}
		}
		//寻找最快的配送内容
		for(int i = 0;i<list.size();i++){
			ShopDelivery sd = list.get(i);
			JSONObject obj = map.get(sd.getVehicle());
			if(obj == null){
				continue;
			}
			Double distance = obj.getDouble("distance");
			if(distance>=sd.getMinDelivery() && distance<sd.getMaxDelivery()){
				if(mapResult.size()==0){
					mapResult.put("shopDelivery", sd);
					mapResult.put("distributionAssessment", obj);
				}else{
					Double duration = obj.getDouble("duration");
					JSONObject ad = (JSONObject)mapResult.get("distributionAssessment");
					Double durationAD = ad.getDouble("duration");
					if(duration<durationAD){
						mapResult.put("shopDelivery", sd);
						mapResult.put("distributionAssessment", obj);
					}
				}
			}
		}
		if(mapResult.size()==0){
			throw new ShopDeliveryNotWithinScopeException("不在配送范围内");
		}

		ShopDeliveryInfoVO infoVo = new ShopDeliveryInfoVO();
		ShopDelivery shopDelivery = (ShopDelivery)mapResult.get("shopDelivery");
		if(shopDelivery.getType().equals(ShopDeliveryType.DISTANCE.toIntValue())){
			infoVo.setType(ShopDeliveryType.DISTANCE.toStringText());
		}else if(shopDelivery.getType().equals(ShopDeliveryType.TOWN.toIntValue())){
			infoVo.setType(ShopDeliveryType.TOWN.toStringText());
		}else if(shopDelivery.getType().equals(ShopDeliveryType.CITY.toIntValue())){
			infoVo.setType(ShopDeliveryType.CITY.toStringText());
		}else if(shopDelivery.getType().equals(ShopDeliveryType.PROVINCE.toIntValue())){
			infoVo.setType(ShopDeliveryType.PROVINCE.toStringText());
		}else{
			infoVo.setType(ShopDeliveryType.UNLIMITED.toStringText());
		}
		
		if(shopDelivery.getVehicle().equals(ShopDeliveryVehicle.BICYCLE.toIntValue())){
			infoVo.setVehicle(ShopDeliveryVehicle.BICYCLE.toStringText());
		}else if(shopDelivery.getVehicle().equals(ShopDeliveryVehicle.ELECTRIC_VEHICLE.toIntValue())){
			infoVo.setVehicle(ShopDeliveryVehicle.ELECTRIC_VEHICLE.toStringText());
		}else if(shopDelivery.getVehicle().equals(ShopDeliveryVehicle.TRANSIT.toIntValue())){
			infoVo.setVehicle(ShopDeliveryVehicle.TRANSIT.toStringText());
		}else if(shopDelivery.getVehicle().equals(ShopDeliveryVehicle.AUTOMOBILE.toIntValue())){
			infoVo.setVehicle(ShopDeliveryVehicle.AUTOMOBILE.toStringText());
		}else{
			infoVo.setVehicle(ShopDeliveryVehicle.OTHER.toStringText());
		}
		
		infoVo.setCost(shopDelivery.getCost());
		infoVo.setThreshold(shopDelivery.getThreshold());
		infoVo.setFullPriceReduction(shopDelivery.getFullPriceReduction());
		
		mapResult.put("shopDelivery", infoVo);
		//设定预计到达时间
		JSONObject ad = (JSONObject)mapResult.get("distributionAssessment");
		Double durationAD = ad.getDouble("duration")*60;
		Long log = durationAD.longValue()*1000;
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date date = new Date(new Date().getTime()+log);
		ad.put("estimate", dateFormat.format(date));
		//需要分钟
		if(ad.get("duration").toString().equals("0")){
			ad.put("duration", "无法预估时间");
		}
		//添加到返回结果集中
		mapResult.put("distributionAssessment", ad);
		vo.setData(mapResult);
		return vo;
	}
	


}
